import wepy from 'wepy'
import Modal from './modal'
import auth from '../api/auth'

// HTTP工具类
export default class Http {
  static baseUrl = wepy.$instance.globalData.baseUrl;
  static excludeUrl = ['updateToken', 'user_reg', 'login', 'bind'];// 排除需要登录的url

  static async request(method, url, data, loading = false) {
    if (loading) {
      Modal.loading()
    }
    const param = {
      url: this.baseUrl + url,
      method: method,
      data: data
    }
    const res = await wepy.request(param)

    if (this.isSuccess(res)) {
      return res.data.data
    } else {
      if (res.data.code == -1) {
        console.log('isNeedLogin,需要登录')
        let resp = await auth.login()
        if (resp === true) {
          const resAgain = await wepy.request(param)
          if (this.isSuccess(resAgain)) {
            return resAgain.data.data
          }
        }
      }
      var errMsg = res.data.msg
      if(errMsg==null || errMsg == '' || errMsg == '') errMsg = '请求失败'
      console.log('[数据异常]', res)
      return { 'errMsg': errMsg }
    }
  }

  static async isNeedLogin(res) {
    const wxData = res.data
    if (wxData.code === -1) {
      console.log('isNeedLogin,需要登录')
      let resp = await auth.user({ block: false, redirect: false, isNeedRoute: false })
      if (!resp) {
        return false
      }
      return true
    }
    return false
  }

  /**
   * 判断请求是否成功
   */
  static isSuccess(res) {
    if (res && res.data && res.data.data && (res.data.code === 0 || res.data.code === '0')) {
      return true
    } else {
      return false
    }
  }
  /**
   * 构造上传文件头部
   */
  static createAuthHeaderFile () {
    let token = wepy.$instance.globalData.token;
    const header = {};
    // header['Content-Type'] = 'multipart/form-data'
    if(token == null || token == undefined || token == '')
      token = wepy.getStorageSync("token")
    if (token) {
      header['token'] = token;
    }
    return header;
  }
  /**
   * 异常
   */
  static requestException(res) {
    const error = {}
    error.statusCode = res.statusCode
    const wxData = res.data
    const serverData = wxData.data
    if (serverData) {
      error.serverCode = wxData.code
      error.message = serverData.message
      error.serverData = serverData
    }
    return error
  }

  static get(url, data, loading = false) {
    return this.request('GET', url, data, loading)
  }

  static put(url, data, loading = false) {
    return this.request('PUT', url, data, loading)
  }

  static post(url, data, loading = false) {
    return this.request('POST', url, data, loading)
  }

  static patch(url, data, loading = false) {
    return this.request('PATCH', url, data, loading)
  }

  static delete(url, data, loading = false) {
    return this.request('DELETE', url, data, loading)
  }
}
